package com.xujie.chat.server.handler;

import com.xujie.chat.message.EncryptUtils;
import com.xujie.chat.message.MessageType;
import com.xujie.chat.message.MsgHeader;
import com.xujie.chat.message.MyMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.ObjectUtil;
import io.netty.util.internal.StringUtil;

/**
 * @author Xujie
 * @since 2024/12/29 16:44
 **/


public class MessageFilterHandler extends ChannelInboundHandlerAdapter {
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		// 过滤掉消息
		MyMessage message = (MyMessage) msg;
		MsgHeader myHeader = message.getMyHeader();
		if (myHeader == null ||
						myHeader.getType() == MessageType.MESSAGE.value() && StringUtil.isNullOrEmpty(myHeader.getToClientId()) ||
						myHeader.getType() == MessageType.MESSAGE.value() && message.getBody() == null ||
						!StringUtil.isNullOrEmpty(myHeader.getMd5()) && !checkMd5(message)
		) {
			// 丢弃消息
			ReferenceCountUtil.release(msg);
		} else {
			super.channelRead(ctx, msg);
		}
	}

	private boolean checkMd5(MyMessage myMessage) {
		MsgHeader myHeader = myMessage.getMyHeader();
		String md5 = myHeader.getMd5();
		if (md5.equals(EncryptUtils.encrypt(myHeader.getToClientId() + myMessage.getBody().toString()))) {
			return true;
		} else {
			return false;
		}
	}
}
